package com.derekandbritt.booST;

import android.content.Intent;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.derekandbritt.booST.data.Challenge;
import com.derekandbritt.booST.data.EmotionLevel;
import com.derekandbritt.booST.data.User;
import com.derekandbritt.booST.exceptions.ConnectionException;
import com.derekandbritt.booST.exceptions.DataFormatException;
import com.derekandbritt.booST.exceptions.GenericException;
import com.derekandbritt.booST.preferences.PreferencesActivity;

public class booST extends booSTActivity {
	
	public static final String ENERGY_HISTORY = "energyHistory";
	public static final String EMOTIONAL_STATUS = "emotionalStatus";
	
    public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
    	MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu, menu);
        return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_refresh:
                refresh();
                return true;
        	case R.id.menu_settings:
        		Intent intent = new Intent();
        		intent.setClass(this, PreferencesActivity.class);
        		startActivity(intent);
        		return true;
        	case R.id.menu_quit:
        	    this.clearSavedAuthentication();
        	    this.finish();
        	    return true;
        }
        return false;
    }
    
    protected void handleResume() throws ConnectionException, DataFormatException {
    	displayContent();
    }
    
    public void onDestroy() {
        super.onDestroy();
        
        // notify the booST server that we are signing out
        try { booSTEndpoint.logout(); }
        catch (GenericException e) { handleError(e, true); }
    }
    
    private void configureMessages() throws ConnectionException, DataFormatException {
    	
    	TextView challengeHistoryLink = (TextView)findViewById(R.id.ChallengeHistoryLink);
    	challengeHistoryLink.setOnClickListener(new OnClickListener() {

			public void onClick(View view) {
				Intent intent = new Intent();
				intent.setClass(view.getContext(), ChallengeHistory.class);
				view.getContext().startActivity(intent);
			}     		
    	});
    	
    	Challenge[] challenges = booSTEndpoint.getActiveChallenges();
    	TextView challengeCount = (TextView)findViewById(R.id.ChallengeCount);
    	if(challenges.length == 1) { challengeCount.setText("1 Active Challenge"); }
    	else { challengeCount.setText(challenges.length + " Active Challenges"); }
    	challengeCount.setOnClickListener(new OnClickListener() {

            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(view.getContext(), ChallengeHistory.class);
                intent.putExtra(ChallengeHistory.STATUS_KEY, ChallengeHistory.STATUS_ACTIVE);
                view.getContext().startActivity(intent);
            }           
        });
    }
    
    protected void displayContent() throws ConnectionException, DataFormatException {
    	
    	setContentView(R.layout.main);
    	
    	configurePersonalStatus();
    	configureMessages();
    	
        TableLayout table = (TableLayout)findViewById(R.id.Main_FriendsTable);
        for(User friend : booSTEndpoint.getFriends()) {
        	table.addView(generateTableRow(friend));
        }
    }
    
    private TableRow generateTableRow(final User friend) throws ConnectionException, DataFormatException {
    	    	
    	TableRow row = new TableRow(this);
    	row.setPadding(0, 8, 0, 0);
    	
    	//available icon
    	ImageView status = new ImageView(this);
    	status.setPadding(0, 0, 5, 0);
    	if(friend.isOnline()) {
    		status.setImageResource(R.drawable.available);
    	} else {
    		status.setImageResource(R.drawable.away);
    	}
    	
    	// friends name
    	TextView name = new TextView(this);
    	name.setMinWidth(125);
    	name.setMaxWidth(125);
    	name.setMaxLines(1);
    	name.setEllipsize(TextUtils.TruncateAt.END);
    	name.setText(osEndpoint.getFullName(friend.userID));
    	
    	// energy level
    	TextView energy = new TextView(this);
    	
    	if(friend.currentEnergy != null) {
    	
    		double value = friend.currentEnergy.getLevel();
    		
			energy.setText("(" + value + ")");
			if(value > 0)
				energy.setTextColor(this.getResources().getColorStateList(R.color.energy_positive));
			else 
				energy.setTextColor(this.getResources().getColorStateList(R.color.energy_negative));
			
    	} else {
    		energy.setText("??");
    	}
    	
    	// emotion icon
    	ImageView emotion = new ImageView(this);
    	emotion.setPadding(5, 0, 0, 0);
    	
    	EmotionLevel emotionLevel = friend.currentEmotion;
    	
    	if(emotionLevel == null) {
    		emotion.setImageResource(R.drawable.frown);
    		emotion.setVisibility(View.INVISIBLE);
    	}
    	else if(emotionLevel.getLevel() >= 6)
    		emotion.setImageResource(R.drawable.smile);
    	else if(emotionLevel.getLevel() >= 4)
    		emotion.setImageResource(R.drawable.undecided);
    	else
    		emotion.setImageResource(R.drawable.frown);
    	
    	// challenge link
    	TextView challenge = new TextView(this);
    	challenge.setPadding(15, 0, 0, 0);
    	challenge.setFocusable(true);
    	challenge.setTextColor(((TextView)findViewById(R.id.ChallengeHistoryLink)).getTextColors());
    	challenge.setText("Send Challenge");
    	challenge.setOnClickListener(new OnClickListener() {

			public void onClick(View view) {
				Intent intent = new Intent();
				intent.setClass(view.getContext(), SendChallenge.class);
				intent.putExtra(SendChallenge.RECIPIENT_KEY, friend.userID);
				view.getContext().startActivity(intent);
			} 
    		
    	});
    	
    	row.addView(status);
    	row.addView(name);
    	row.addView(energy);
    	row.addView(emotion);
    	row.addView(challenge);
    	return row;
    }
}